import {
  Controller,
  Get,
  Post,
  Inject,
  Body,
  Param,
  Del,
  Query
} from '@midwayjs/decorator';
import * as fs from 'fs';
import { Context } from '@midwayjs/koa';
// import { createReadStream } from 'fs';
// import { createReadStream, existsSync } from 'fs';
import { FirmwareWristbandService } from '../../service/firmware/firmware_wristband.service';
// import { FirmwareType } from '../../entity/enums';
import { resBuild } from '@utils/resBuild'; // 导入 resBuild 工具类;
@Controller('/firmware_wristband')
export class FirmwareWristbandController {
  @Inject()
  ctx: Context; // 注入上下文对象
  @Inject()
  firmwareWristbandService: FirmwareWristbandService;

  // 创建固件
  @Post('/create')
  async create(@Body() body) {
    console.log('body', body);
    try {
      const { name, version, firmware, path, desc, raw, fileid } = body;
      const result = await this.firmwareWristbandService.createFirmware(
        name,
        version,
        firmware,
        path,
        desc,
        raw,
        fileid
      );
      console.log('result', result);
      return resBuild.success();
    } catch (error) {
      return resBuild.fail('创建固件出错:', error);
    }
  }


  // 获取所有固件
  // @Get('/list')
  // async list() {
  //   const firmwares = await this.firmwareWristbandService.getAllFirmware();
  //   const filteredFirmwares = firmwares.filter(fw => fw.deleted !== true);
  //   return resBuild.data(filteredFirmwares);
  // }

  // 根据 name / version 查询对应固件
  @Get('/list')
  async list(@Query('name') name?: string, @Query('version') version?: string) {
    const firmwares = await this.firmwareWristbandService.getAllFirmware(name, version);
    return resBuild.data(firmwares);
  }
  // 获取单个固件
  @Get('/:id')
  async getById(@Param('id') id: number) {
    const firmware = await this.firmwareWristbandService.getFirmwareById(id);
    if (!firmware) return { success: false, message: '固件不存在' };
    return resBuild.data(firmware);
  }

  // **更新固件**
  @Post('/update/:id')
  async update(@Param('id') id: number, @Body() body) {
    return await this.firmwareWristbandService.updateFirmware(id, body);
    // console.log('updatebody',body)
    // try {
    //   const updatedFirmware =
    //     await this.firmwareWristbandService.updateFirmware(id, body);
    //     console.log('result',updatedFirmware)
    //   if (!updatedFirmware) return resBuild.success('更新成功！');
    // } catch (error) {
    //   return resBuild.fail('更新失败，固件不存在');
    // }
  }

  // **删除固件**
  @Del('/delete/:id')
  async delete(@Param('id') id: number) {
    return await this.firmwareWristbandService.deleteFirmware(id);
    // const deleted = await this.firmwareWristbandService.deleteFirmware(id);
    // if (!deleted) return { success: false, message: '删除失败，固件不存在' };
    // return { success: true, message: '删除成功' };
  }

  // 下载指定固件并下发到手环
  @Get('/download/:gatewayId/:firmwareId')
  async downloadFirmware(
    @Param('gatewayId') gatewayId: string,
    @Param('firmwareId') firmwareId: number
  ) {
    // 查询指定 ID 的固件
    const firmware = await this.firmwareWristbandService.getFirmwareById(
      firmwareId
    );
    if (!firmware) {
      return { code: 404, message: `固件 ID ${firmwareId} 不存在` };
    }

    const filePath = firmware.path;
    if (!filePath || !fs.existsSync(filePath)) {
      return { code: 404, message: `固件文件 ${filePath} 不存在` };
    }

    // 模拟固件下发到手环
    this.firmwareWristbandService.sendFirmwareToWristband(gatewayId, firmware);

    return {
      code: 200,
      message: `固件 ${firmware.name} 已成功下发到手环`,
      data: { name: firmware.name, version: firmware.version, file: filePath },
    };
  }


  // 下载固件
  @Get('/downloadUrl')
  async downloadUrlFirmware(
    @Query('fileid') fileid: string,
    @Query('firmware') firmware: string) {
    console.log('Received request with fileid:', fileid, 'and firmware:', firmware);
    try {
      const filepath = await this.firmwareWristbandService.getFirmwareFileById(fileid);
      // const uploadDir = path.join(__dirname, filepath);
      console.log('绝对路径:', filepath);
      // 检查文件是否存在
      if (!fs.existsSync(filepath.path)) {
        // this.ctx.status = 404;
        // this.ctx.body = 'File not found on server';
        return resBuild.fail("下载失败，文件不存在");
      } else {
        try {
          // 创建文件流并返回给客户端
          const fileStream = fs.createReadStream(filepath.path);
          fileStream.on('error', (error) => {
            console.error('文件流读取失败:', error);
            this.ctx.status = 500;
            this.ctx.body = '文件流读取失败';
          });
          // 设置响应头
          this.ctx.set('Content-Disposition', `attachment; filename=${filepath.name}`);
          this.ctx.set('Content-Type', 'application/octet-stream');
          this.ctx.status = 200;
          // 返回文件流
          this.ctx.body = fileStream;
        } catch (error) {
          this.ctx.status = 500;
          this.ctx.body = 'Failed to download file';
          return resBuild.fail("文件下载失败")
        }
      }

    } catch (err) {
      console.log('err', err)
      return resBuild.fail("文件下载失败", err)
    }
  }

}
